<template>
	<view class="pb-150">
		<!-- 导航栏 -->
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill"></image>
		<u-navbar title="林业品牌管理" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder>
		</u-navbar>

		<!-- 搜索区域 -->
		<view class="search-bar">
			<u-search v-model="query.keyword" placeholder="请输入品牌名称" showAction actionText="搜索" @search="onSearch"
				:actionStyle="{ color: '#0A993B', fontSize: '28rpx' }" :bgColor="'#fff'" :height="30"
				:inputStyle="{ fontSize: '28rpx' }" />
		</view>

		<!-- 列表 -->
		<view v-for="item in filteredList" :key="item.id" class="card">
			<view class="row top">
				<text class="name">{{ item.name }}</text>
			</view>
			<view class="meta">排序：{{ item.order }} 类型：{{ item.type }}</view>
			<view class="ops">
				<u-button size="small" text="编辑" @click="onEdit(item)"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }" />
				<u-button size="small" text="删除" type="error" plain @click="onDelete(item)"
					:customStyle="{ border: '1px solid #0A993B', borderColor: '#0A993B', color: '#0A993B' }" />
			</view>
		</view>

		<!-- 空状态 -->
		<view v-if="filteredList.length === 0 && !loading" class="empty">
			<u-empty mode="data" icon="data"></u-empty>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<u-loading-icon mode="spinner" size="28"></u-loading-icon>
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 没有更多数据提示 -->
		<view v-if="!hasMore && list.length > 0" class="no-more">
			<text class="no-more-text">没有更多数据了</text>
		</view>

		<!-- 编辑弹窗 -->
		<u-popup :show="showEdit" mode="center" round="12" @close="showEdit = false">
			<view class="edit-wrap">
				<view class="edit-title">{{ isAdd ? '添加品牌' : '编辑品牌' }}</view>

				<view class="form-row">
					<text class="label"><text class="req">*</text> 品牌名称</text>
					<u--input v-model="editForm.name" placeholder="请输入品牌名称" :customStyle="inputStyle" />
				</view>

				<view class="form-row" @click="showType = true">
					<text class="label"><text class="req">*</text> 类型</text>
					<view class="picker-input">
						{{ editForm.type || '请选择品牌类型' }}
						<u-icon name="arrow-right" size="16" />
					</view>
				</view>

				<view class="form-row">
					<text class="label"><text class="req">*</text> 排序</text>
					<u-number-box v-model="editForm.order" :min="1" :max="9999" integer :step="1" />
				</view>
				<view class="btns">
					<u-button text="取消" @click="showEdit = false" />
					<u-button text="保存" type="primary" @click="saveEdit"
						:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }" />
				</view>
			</view>
		</u-popup>

		<view @tap="onAdd" class="w-690 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
			style="bottom: 68rpx;left: 30rpx;">
			添加
		</view>

		<!-- 类型选择器 -->
		<u-picker :show="showType" :columns="typeColumns" @confirm="typeConfirm" @cancel="showType = false" />
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import { getBrandType, getBrandList, addBrand, updateBrand, deleteBrand } from '@/api/economicforest'

export default {
	mixins: [navbarMixin],
	data() {
		return {
			query: { keyword: '' },
			list: [],
			loading: false,
			pageNum: 1,
			pageSize: 10,
			hasMore: true,
			showEdit: false,
			isAdd: true,
			editForm: { id: null, name: '', order: 1, type: '' },
			showType: false,
			typeColumns: [[
				{ text: '地理标识', value: '1' },
				{ text: '名优特产', value: '2' },
				{ text: '生态产品', value: '3' }
			]],
			inputStyle: { height: '72rpx', padding: '0 24rpx', margin: '12rpx 0' }
		}
	},
	computed: {
		filteredList() {
			const keyword = this.query && this.query.keyword ? this.query.keyword : ''
			return (this.list || []).filter(v => !keyword || (v.name && v.name.includes(keyword)))
		}
	},
	async 	onLoad() {
		// 获取品牌类型
		await this.getBrandTypes()
		// 获取品牌列表
		await this.getBrandList()
	},
	onReachBottom() {
		// 触底加载更多
		if (this.hasMore && !this.loading) {
			this.getBrandList()
		}
	},
	mounted() {
		console.log('组件已挂载，当前typeColumns:', this.typeColumns)
	},
	methods: {
		// 获取品牌类型
		async getBrandTypes() {
			try {
				const response = await getBrandType()
				console.log('品牌类型API响应:', response)

				if (response && response.data && Array.isArray(response.data)) {
					console.log('品牌类型原始数据:', response.data)
					// 转换数据格式为u-picker需要的格式
					const typeValues = response.data.map(item => ({
						text: item.dictLabel || '未知类型',
						value: item.dictValue || item.value
					}))

					console.log('转换后的数据:', typeValues)
					this.typeColumns = [typeValues]
					console.log('设置后的typeColumns:', this.typeColumns)
				} else {
					console.log('API响应格式不正确:', response)
				}
			} catch (error) {
				console.error('获取品牌类型失败:', error)
			}
		},
		// 获取品牌列表
		async getBrandList(isRefresh = false) {
			if (this.loading) return

			this.loading = true

			try {
				// 构建请求参数
				const params = {
					pageNum: isRefresh ? 1 : this.pageNum,
					pageSize: this.pageSize
				}

				// 添加搜索条件
				if (this.query.keyword && this.query.keyword.trim()) {
					params.name = this.query.keyword.trim()
				}

				console.log('请求参数:', params)

				const response = await getBrandList(params)
				console.log('品牌列表数据:', response)

				if (response && response.rows) {
					// 转换数据格式以匹配现有的显示结构
					const convertedData = response.rows.map(item => ({
						id: item.id,
						name: item.name || '未知品牌',
						order: item.orderNum || 0,
						type: this.getTypeText(item.typeId),
						// 保留原始数据
						originalData: item
					}))

					if (isRefresh) {
						this.list = convertedData
						this.pageNum = 1
					} else {
						this.list = [...this.list, ...convertedData]
					}

					// 判断是否还有更多数据
					this.hasMore = response.rows.length === this.pageSize
					if (this.hasMore) {
						this.pageNum++
					} else {
						this.hasMore = false
					}
				}
			} catch (error) {
				console.error('获取品牌列表失败:', error)
				uni.showToast({
					title: '获取数据失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		// 获取类型文本
		getTypeText(typeId) {
			const typeMap = {
				1: '地理标识',
				2: '名优特产',
				3: '生态产品'
			}
			return typeMap[typeId] || '未知类型'
		},
		// 根据类型名称获取类型ID
		getTypeIdByName(typeName) {
			const typeMap = {
				'地理标识': 1,
				'名优特产': 2,
				'生态产品': 3
			}
			return typeMap[typeName] || null
		},
		async onSearch() {
			this.pageNum = 1
			this.hasMore = true
			await this.getBrandList(true)
		},
		onEdit(item) {
			this.isAdd = false
			this.editForm = {
				id: item.id,
				name: item.name,
				order: item.order,
				type: this.getTypeText(item.originalData?.typeId || 1)
			}
			this.showEdit = true
		},
		onAdd() {
			this.isAdd = true
			const maxOrder = (this.list || []).reduce((m, v) => Math.max(m, Number(v.order || 0)), 0)
			this.editForm = { id: null, name: '', order: maxOrder + 1, type: '' }
			this.showEdit = true
		},
		typeConfirm(e) {
			this.editForm.type = e.value[0].text
			this.showType = false
		},
		async saveEdit() {
			// 验证必填字段
			if (!this.editForm.name || !this.editForm.name.trim()) {
				uni.showToast({ title: '请输入品牌名称', icon: 'none' })
				return
			}
			if (!this.editForm.type) {
				uni.showToast({ title: '请选择品牌类型', icon: 'none' })
				return
			}
			if (!this.editForm.order || this.editForm.order <= 0) {
				uni.showToast({ title: '请输入排序', icon: 'none' })
				return
			}

			// 获取类型ID
			const typeId = this.getTypeIdByName(this.editForm.type)
			if (!typeId) {
				uni.showToast({ title: '品牌类型无效', icon: 'none' })
				return
			}

			if (this.isAdd) {
				// 添加品牌
				try {
					uni.showLoading({ title: '添加中...' })

					const submitData = {
						name: this.editForm.name.trim(),
						typeId: parseInt(typeId), // 确保typeId是整数类型
						orderNum: this.editForm.order.toString()
					}

					console.log('提交数据:', submitData)

					const response = await addBrand(submitData)

					uni.hideLoading()

					if (response && response.code === 200) {
						uni.showToast({ title: '添加成功', icon: 'success' })
						this.showEdit = false
						// 刷新列表
						await this.getBrandList(true)
					} else {
						uni.showToast({ title: response?.msg || '添加失败', icon: 'none' })
					}
				} catch (error) {
					uni.hideLoading()
					console.error('添加品牌失败:', error)
					uni.showToast({ title: '网络错误，请重试', icon: 'none' })
				}
			} else {
				// 编辑品牌
				try {
					uni.showLoading({ title: '修改中...' })

					const submitData = {
						id: this.editForm.id.toString(), // 确保id是字符串类型
						name: this.editForm.name.trim(),
						typeId: parseInt(typeId), // 确保typeId是整数类型
						orderNum: this.editForm.order.toString()
					}

					console.log('修改数据:', submitData)

					const response = await updateBrand(submitData)

					uni.hideLoading()

					if (response && response.code === 200) {
						uni.showToast({ title: '修改成功', icon: 'success' })
						this.showEdit = false
						// 刷新列表
						await this.getBrandList(true)
					} else {
						uni.showToast({ title: response?.msg || '修改失败', icon: 'none' })
					}
				} catch (error) {
					uni.hideLoading()
					console.error('修改品牌失败:', error)
					uni.showToast({ title: '网络错误，请重试', icon: 'none' })
				}
			}
		},
		async onDelete(item) {
			uni.showModal({
				title: '提示',
				content: `确定删除"${item.name}"吗？`,
				success: async ({ confirm }) => {
					if (confirm) {
						try {
							uni.showLoading({ title: '删除中...' })

							console.log('删除品牌ID:', item.id)

							const response = await deleteBrand(item.id)

							uni.hideLoading()

							if (response && response.code === 200) {
								uni.showToast({ title: '删除成功', icon: 'success' })
								// 刷新列表
								await this.getBrandList(true)
							} else {
								uni.showToast({ title: response?.msg || '删除失败', icon: 'none' })
							}
						} catch (error) {
							uni.hideLoading()
							console.error('删除品牌失败:', error)
							uni.showToast({ title: '网络错误，请重试', icon: 'none' })
						}
					}
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 750rpx;

	z-index: 1;
}

.search-bar {
	display: flex;
	gap: 16rpx;
	padding: 20rpx;
}

.btn-search {
	min-width: 140rpx;
}

.card {
	margin: 16rpx 20rpx;
	padding: 20rpx;
	background: #fff;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.row.top {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.name {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
}

.ops {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 22rpx;
}

.ops>.u-button:first-child {
	margin-right: 12rpx;
}

.meta {
	margin-top: 12rpx;
	color: #666;
}

.edit-wrap {
	width: 620rpx;
	padding: 24rpx;
}

.btns {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.btns>.u-button:first-child {
	margin-right: 12rpx;
}

.edit-title {
	text-align: center;
	font-size: 30rpx;
	font-weight: 600;
	margin-bottom: 12rpx;
}

.form-row {
	margin: 24rpx 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.label {
	display: block;
	color: #333;
	font-size: 26rpx;
	margin-bottom: 8rpx;
}

.req {
	color: #e54d42;
	margin-right: 6rpx;
}

.type-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0;
}

.type-label {
	color: #333;
	font-size: 28rpx;
}

.picker-input {
	color: #666;
	display: flex;
	align-items: center;
}

.empty {
	padding: 80rpx 0;
	text-align: center;
}

.loading {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 40rpx 0;
}

.loading-text {
	margin-left: 10rpx;
	color: #999;
	font-size: 26rpx;
}

.no-more {
	padding: 40rpx 0;
	text-align: center;
}

.no-more-text {
	color: #999;
	font-size: 24rpx;
}
</style>